package com.qujia.customer.service.impl;

import com.github.pagehelper.PageHelper;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.MathUtil;
import com.qujia.customer.domain.*;
import com.qujia.customer.domain.dto.CustomerCardChangeDto;
import com.qujia.customer.domain.from.UserBalanceForm;
import com.qujia.customer.domain.vo.Integral;
import com.qujia.customer.domain.vo.UserBalanceSumVO;
import com.qujia.customer.domain.vo.UserBalanceVO;
import com.qujia.customer.enums.CardRecordType;
import com.qujia.customer.mapper.CustomerCardSettingDetailContentMapper;
import com.qujia.customer.mapper.CustomerCardSettingMapper;
import com.qujia.customer.mapper.CustomerCardUseRecordMapper;
import com.qujia.customer.mapper.CustomerElectronicCardMapper;
import com.qujia.customer.service.ICustomerCardUseRecordService;
import com.qujia.customer.service.ICustomerElectronicCardService;
import com.qujia.customer.vo.ElectronicCardListVO;
import com.qujia.customer.vo.ElectronicCardTypeListVO;
import com.qujia.enums.integralTypeEnum;
import com.qujia.integral.domain.CustomerPointsRecord;
import com.qujia.integral.mapper.CustomerPointsRecordMapper;
import com.qujia.integral.service.ICustomerPointsRecordService;
import com.qujia.system.domain.SysAppUserInfoUser;
import com.qujia.system.domain.SysEnterpriseUser;
import com.qujia.system.domain.SysStationUser;
import com.qujia.system.mapper.AppUserInfoUserMapper;
import com.qujia.system.service.IAppUserInfoUserService;
import com.qujia.system.service.ISysEnterpriseUserService;
import com.qujia.system.service.ISysStationUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户电子会员卡（储蓄卡）Service业务层处理
 * 
 * @author qujia
 * @date 2021-04-12
 */
@Service
@Slf4j
public class CustomerElectronicCardServiceImpl implements ICustomerElectronicCardService 
{
    @Autowired
    private CustomerElectronicCardMapper customerElectronicCardMapper;
    @Autowired
    private ISysEnterpriseUserService enterpriseUserService;
    @Autowired
    private CustomerCardSettingMapper customerCardSettingMapper;
    @Autowired
    private ISysStationUserService stationUserService;

    @Resource
    private ICustomerCardUseRecordService customerCardUseRecordService;

    @Resource
    private IAppUserInfoUserService appUserInfoUserService;

    @Resource
    private ISysStationUserService sysStationUserService;

    @Autowired
    private ICustomerPointsRecordService customerPointsRecordService;

    @Autowired
    private AppUserInfoUserMapper appUserInfoMapper;

    @Autowired
    private CustomerCardSettingDetailContentMapper customerCardSettingDetailContentMapper;


    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;

    @Autowired
    private CustomerPointsRecordMapper customerPointsRecordMapper;


    /**
     * 查询客户电子会员卡（储蓄卡）
     * 
     * @param id 客户电子会员卡（储蓄卡）ID
     * @return 客户电子会员卡（储蓄卡）
     */
    @Override
    public CustomerElectronicCard selectCustomerElectronicCardById(Long id)
    {
        return customerElectronicCardMapper.selectCustomerElectronicCardById(id);
    }

    @Override
    public CustomerElectronicCard selectCustomerElectronicCard(Long id) {
        return customerElectronicCardMapper.selectCustomerElectronicCard(id);
    }

    /**
     * 查询客户电子会员卡（储蓄卡）列表
     * 
     * @param customerElectronicCard 客户电子会员卡（储蓄卡）
     * @return 客户电子会员卡（储蓄卡）
     */
    @Override
    public List<CustomerElectronicCard> selectCustomerElectronicCardList(CustomerElectronicCard customerElectronicCard)
    {
        return customerElectronicCardMapper.selectCustomerElectronicCardList(customerElectronicCard);
    }

    /**
     * 新增客户电子会员卡（储蓄卡）
     * 
     * @param customerElectronicCard 客户电子会员卡（储蓄卡）
     * @return 结果
     */
    @Override
    public int insertCustomerElectronicCard(CustomerElectronicCard customerElectronicCard)
    {
        customerElectronicCard.setCreateTime(DateUtils.getNowDate());
        return customerElectronicCardMapper.insertCustomerElectronicCard(customerElectronicCard);
    }

    /**
     * 修改客户电子会员卡（储蓄卡）
     * 
     * @param customerElectronicCard 客户电子会员卡（储蓄卡）
     * @return 结果
     */
    @Override
    public int updateCustomerElectronicCard(CustomerElectronicCard customerElectronicCard)
    {
        customerElectronicCard.setRecentlyTime(new Date());
        return customerElectronicCardMapper.updateCustomerElectronicCard(customerElectronicCard);
    }

    private String generateOrdNo(){
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo = System.currentTimeMillis() + result;
        return ordNo;
    }

    @Override
    @Transactional
    public AjaxResult updateUserReocrd(CustomerCardChangeDto customerCardChangeDto) {

        CustomerElectronicCard customerElectronicCardRes = selectCustomerElectronicCard(customerCardChangeDto.getId());

        CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
        customerCardUseRecord.setOrderNo(generateOrdNo());

        Long stationId2 = customerElectronicCardRes.getStationId2();
        if(Objects.nonNull(stationId2)){
            customerCardUseRecord.setStationId(customerElectronicCardRes.getStationId2().intValue());
        }else {
            if(Objects.isNull(customerCardChangeDto.getStationId())){
                return AjaxResult.error("请选择油站主体");
            }
            customerCardUseRecord.setStationId(customerCardChangeDto.getStationId().intValue());
        }
        if (Objects.isNull(customerCardUseRecord.getStationId())) {
            return AjaxResult.error("请选择油站主体");
        }
        SysStationUser sysStationUser = sysStationUserService.selectSysStationUserById(Long.valueOf(customerCardUseRecord.getStationId()));
        SysAppUserInfoUser sysAppUserInfoUser = new SysAppUserInfoUser();
        sysAppUserInfoUser.setMobilePhone(customerElectronicCardRes.getMobilePhone());
        sysAppUserInfoUser.setStationId(sysStationUser.getEnterpriseId());
        SysAppUserInfoUser one = appUserInfoUserService.getOne(sysAppUserInfoUser);
        if (one != null) {
            customerCardUseRecord.setCustomerName(one.getBlogNickName());
            customerCardUseRecord.setCustomerNo(one.getMemberCode());
        }
        customerCardUseRecord.setEnterpriseId(sysStationUser.getEnterpriseId());
        customerCardUseRecord.setMobilePhone(customerElectronicCardRes.getMobilePhone());
        BigDecimal afterAmt = customerCardChangeDto.getAmt();
        BigDecimal beforeAmt = customerElectronicCardRes.getAmt();

        if(beforeAmt.compareTo(afterAmt) == 0){
            return AjaxResult.error("金额不能与调整前余额相同");
        }

        //插入电子卡充值消费记录
        boolean add = afterAmt.subtract(beforeAmt).compareTo(BigDecimal.ZERO) > 0;
        customerCardUseRecord.setUsageType(add ? "+" : "-");
        customerCardUseRecord.setPayType( add ? CardRecordType.MANUAL_ADD.getKey() : CardRecordType.MANUAL_SUB.getKey());
        customerCardUseRecord.setCardOilsType(customerElectronicCardRes.getCardOilsType());
        customerCardUseRecord.setAmt(afterAmt.subtract(beforeAmt).abs());
        customerCardUseRecord.setBalance(afterAmt);
        customerCardUseRecord.setCreateTime(new Date());
        customerCardUseRecord.setPresentAmt(BigDecimal.ZERO);
        customerCardUseRecord.setStatus("1");
        customerCardUseRecord.setReason(customerCardChangeDto.getReason());
        customerCardUseRecord.setOperator(customerCardChangeDto.getOperator());
        customerCardUseRecordService.insertCustomerCardUseRecord(customerCardUseRecord);
        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
        customerElectronicCard.setRecentlyTime(new Date());
        customerElectronicCard.setId(customerCardChangeDto.getId());
        customerElectronicCard.setAmt(customerCardChangeDto.getAmt());

        updateCustomerElectronicCard(customerElectronicCard);

        //todo 发券

        //todo 推送消息
        Integer messagePush = customerCardChangeDto.getMessagePush();
        if (messagePush == 1){

        }

        return AjaxResult.success("调整余额成功");
    }

    /**
     * 批量删除客户电子会员卡（储蓄卡）
     * 
     * @param ids 需要删除的客户电子会员卡（储蓄卡）ID
     * @return 结果
     */
    @Override
    public int deleteCustomerElectronicCardByIds(Long[] ids)
    {
        return customerElectronicCardMapper.deleteCustomerElectronicCardByIds(ids);
    }

    /**
     * 删除客户电子会员卡（储蓄卡）信息
     * 
     * @param id 客户电子会员卡（储蓄卡）ID
     * @return 结果
     */
    @Override
    public int deleteCustomerElectronicCardById(Long id)
    {
        return customerElectronicCardMapper.deleteCustomerElectronicCardById(id);
    }

    /**
     * 查询电子会员数据
     */
    @Override
    public CustomerElectronicCard listSum(CustomerElectronicCard customerElectronicCard) {
        return customerElectronicCardMapper.listSum(customerElectronicCard);
    }

    /**
     * 查询电子会员报表数据
     */
    @Override
    public List<CustomerElectronicCard> selectCard(CustomerElectronicCard customerElectronicCard) {
        return customerElectronicCardMapper.selectCard(customerElectronicCard);
    }

    @Override
    public List<CustomerElectronicCard> selectCardPage(CustomerElectronicCard customerElectronicCard) {
        return customerElectronicCardMapper.selectCardPage(customerElectronicCard);
    }

    @Override
    public CustomerElectronicCard listHYData(CustomerElectronicCard customerElectronicCard) {
        return customerElectronicCardMapper.listHYData( customerElectronicCard) ;
    }

    @Override
    public CustomerElectronicCard listJRHYData(CustomerElectronicCard customerElectronicCard) {
        return customerElectronicCardMapper.listJRHYData( customerElectronicCard) ;
    }


    /**
     * 查询电子卡的汇总信息
     */
    @Override
    public List<CustomerElectronicCard> cardUserSum(CustomerElectronicCard customerElectronicCard){
        return  customerElectronicCardMapper.cardUserSum(customerElectronicCard);
    }

    @Override
    public List<ElecSumInfo> getRechargeSum(CustomerCardUseRecord customerCardUseRecord) {


//        List<String> payTypeList = new ArrayList<>();
//        if(Objects.nonNull(customerCardUseRecord) && StringUtils.isNotEmpty(customerCardUseRecord.getPayType())){
//            payTypeList = Arrays.stream(customerCardUseRecord.getPayType().split(",")).collect(Collectors.toList());
//        }
//        customerCardUseRecord.setPayTypeList(payTypeList);
        return customerElectronicCardMapper.getRechargeSum(customerCardUseRecord);
    }

    @Override
    public List<ElecSumInfo> getManualDeduction(CustomerCardUseRecord customerCardUseRecord) {
        return customerElectronicCardMapper.getManualDeduction(customerCardUseRecord);
    }

    @Override
    public List<ElecSumInfo> getConsumeSum(CustomerCardUseRecord customerCardUseRecord) {
//        List<String> payTypeList = new ArrayList<>();
//        if(Objects.nonNull(customerCardUseRecord) && StringUtils.isNotEmpty(customerCardUseRecord.getPayType())){
//            payTypeList = Arrays.stream(customerCardUseRecord.getPayType().split(",")).collect(Collectors.toList());
//        }
//        customerCardUseRecord.setPayTypeList(payTypeList);
        return customerElectronicCardMapper.getConsumeSum(customerCardUseRecord);
    }

    @Override
    public List<ElecSumInfo> getBalanceSum(CustomerElectronicCard customerElectronicCard,boolean cardUseForAll) {
        return customerElectronicCardMapper.getBalanceSum(customerElectronicCard,cardUseForAll);
    }

    @Override
    public List<CustomerElectronicCard> getCustomerElectronicCardListForEnterprise(String mobilePhone, String[] cardTypes, Long enterpriseId){
        CustomerElectronicCard card = new CustomerElectronicCard();
        card.setMobilePhone(mobilePhone);
        card.setCardOilsTypeArray(cardTypes);
        card.setStationId(enterpriseId);
        return customerElectronicCardMapper.getElectronicCardListBycardOilsTypeArray(card);
    }

    @Override
    public List<CustomerElectronicCard> getCustomerElectronicCardListForStation(String mobilePhone, String[] cardTypes, Long stationId){
        CustomerElectronicCard card = new CustomerElectronicCard();
        card.setMobilePhone(mobilePhone);
        card.setCardOilsTypeArray(cardTypes);
        card.setStationId2(stationId);
        return customerElectronicCardMapper.getElectronicCardListBycardOilsTypeArray(card);
    }

    @Override
    public ElectronicCardListVO queryCustomerCardList(String mobilePhone,Long enterpriseId){
        ElectronicCardListVO vo = new ElectronicCardListVO();
        CustomerCardSetting setting = new CustomerCardSetting();
        setting.setEnterpriseId(enterpriseId);
        setting = customerCardSettingMapper.selectCustomerCardSetting(setting);
        if (setting == null || StringUtils.equals("0",setting.getCardEnabledFlag())) {
            // 电子卡未开启
            vo.setCardUseRangeFlag("1");
            vo.setTotalAmt(BigDecimal.ZERO);
            vo.setCardList(Collections.emptyList());
            return vo;
        }
        //开启的电子卡
        if (StringUtils.isBlank(setting.getCardOilsType())) {
            return vo;
        }
        String[] split = setting.getCardOilsType().split(",");
        if (split.length == 0) {
            return vo;
        }
        vo.setCardUseRangeFlag(setting.getCardUseRangeFlag());
        if (StringUtils.equals("1",setting.getCardUseRangeFlag())) {
            // 多站通用时查询列表
            vo.setCardList(getCustomerElectronicCardListForEnterprise(mobilePhone,split,setting.getEnterpriseId()));
            List<CustomerElectronicCard> cardList = vo.getCardList();
            BigDecimal sum = BigDecimal.ZERO;
            for (CustomerElectronicCard card : cardList) {
                card.setTotalAmt(MathUtil.add(card.getAmt(),card.getPresentAmt()));
                if (card.getAmt() != null) {
                    sum = sum.add(card.getAmt());
                }
            }
            vo.setTotalAmt(sum);
        } else {
            // 单站使用时查询列表
            SysStationUser stationUser = new SysStationUser();
            stationUser.setEnterpriseId(enterpriseId);
            stationUser.setDeleteStatus("0");
            stationUser.setStatus("1");
            List<SysStationUser> stationUsers = stationUserService.selectSysStationUserList(stationUser);
            List<CustomerElectronicCard> cardList = new ArrayList<>();
            for (SysStationUser station : stationUsers) {
                List<CustomerElectronicCard> cards = getCustomerElectronicCardListForStation(mobilePhone,split,station.getStationId());
                cardList.addAll(cards);
            }
            List<ElectronicCardTypeListVO> cardTypeList = new ArrayList<>();
            Map<String,ElectronicCardTypeListVO> typeMap = new HashMap<>();
            BigDecimal sum = BigDecimal.ZERO;
            for (CustomerElectronicCard card : cardList) {
                card.setTotalAmt(MathUtil.add(card.getAmt(),card.getPresentAmt()));
                String cardType = card.getCardOilsType();
                ElectronicCardTypeListVO vo1 = typeMap.get(cardType);
                if (vo1 == null) {
                    vo1 = new ElectronicCardTypeListVO();
                    vo1.setCardList(new ArrayList<>());
                    vo1.setCardOilsType(cardType);
                    vo1.setTotalAmt(BigDecimal.ZERO);
                    typeMap.put(cardType,vo1);
                    cardTypeList.add(vo1);
                }
                List<CustomerElectronicCard> list1 = vo1.getCardList();
                list1.add(card);
                if (card.getAmt() != null) {
                    vo1.setTotalAmt(vo1.getTotalAmt().add(card.getTotalAmt()));
                    sum = sum.add(card.getTotalAmt());
                }
                Date old = vo1.getRecentlyTime();
                Date newT = card.getRecentlyTime();
                int c;
                if(old == null){
                    c = -1;
                }else if(newT == null){
                    c = 1;
                }else{
                    c = old.compareTo(newT);
                }
                vo1.setRecentlyTime(c < 0 ? newT : old);
            }
            for (String type : split) {
                ElectronicCardTypeListVO vo1 = typeMap.get(type);
                if (vo1 == null) {
                    vo1 = new ElectronicCardTypeListVO();
                    vo1.setCardOilsType(type);
                    vo1.setTotalAmt(BigDecimal.ZERO);
                    vo1.setCardList(Collections.emptyList());
                    cardTypeList.add(vo1);
                }
            }
            cardTypeList.sort((i1,i2) -> StringUtils.compare(i1.getCardOilsType(),i2.getCardOilsType()));
            vo.setCardTypeList(cardTypeList);
            vo.setTotalAmt(sum);
        }
        return vo;
    }

    @Override
    public int incrCustomerElectronicCardBalance(BigDecimal incrAmt,BigDecimal incrPresentAmt,CustomerElectronicCard card) {
        return customerElectronicCardMapper.incrCustomerElectronicCardBalance(incrAmt,incrPresentAmt,card);
    }

    @Override
    public int insertBatch(List<CustomerElectronicCard> cardList) {
        return customerElectronicCardMapper.insertBatch(cardList);
    }

    @Override
    public BigDecimal getCustomerElectronicCardBalance(String mobilePhone, Integer enterpriseId, boolean cardUseForAll, List<String> types) {
        BigDecimal balance = customerElectronicCardMapper.countCardBalance(mobilePhone,enterpriseId,cardUseForAll,types);
        return balance == null ? BigDecimal.ZERO : balance;
    }

    @Override
    public CustomerElectronicCard getElectronicCardInfo(CustomerElectronicCard customerElectronicCard) {
        return customerElectronicCardMapper.getElectronicCardInfo(customerElectronicCard);
    }

    @Override
    public List<CustomerElectronicCard> queryListOrderByCardType(CustomerElectronicCard customerElectronicCard) {
        return customerElectronicCardMapper.queryListOrderByCardType(customerElectronicCard);
    }

    @Override
    public CustomerElectronicCard getCustomerElectronicCard(String mobilePhone, String cardType, Long stationId, Long enterpriseId) {
        SysEnterpriseUser sysEnterpriseUser = enterpriseUserService.selectSysEnterpriseUserById(enterpriseId);


        CustomerElectronicCard builder = new CustomerElectronicCard();
        builder.setCardOilsType(cardType);
        builder.setMobilePhone(mobilePhone);


        if (StringUtils.equals("1",sysEnterpriseUser.getCardUseRangeFlag())) {
            builder.setStationId(enterpriseId);
        }else{
            builder.setStationId2(stationId);
        }
        return customerElectronicCardMapper.getElectronicCardInfo(builder);
    }

    @Override
    public List<UserBalanceVO> queryUserBalanceVOList(UserBalanceForm form) {


        List<UserBalanceVO> userBalanceVOS = customerElectronicCardMapper.queryUserBalanceVO(form);
        PageHelper.clearPage();
        Map<Long, SysEnterpriseUser> enterpriseMap = new HashMap<>();
        Map<Long,SysStationUser> stationMap = new HashMap<>();
        Map<String,SysAppUserInfoUser> userMap = new HashMap<>();
        for (UserBalanceVO balanceVO : userBalanceVOS) {
            if (balanceVO.getEnterpriseId() != null) {
                Long enterpriseId = balanceVO.getEnterpriseId();
                SysEnterpriseUser sysEnterprise = enterpriseMap.get(enterpriseId);
                if (sysEnterprise == null) {
                    SysEnterpriseUser enterpriseUser = enterpriseUserService.selectSysEnterpriseUserById(enterpriseId);
                    enterpriseMap.put(enterpriseId,enterpriseUser);
                    sysEnterprise = enterpriseUser;
                }
                if (sysEnterprise != null) {
                    balanceVO.setEnterpriseName(sysEnterprise.getEnterpriseName());
                }

            }else if(balanceVO.getStationId() != null){
                Long stationId = balanceVO.getStationId();
                SysStationUser sysStationUser = stationMap.get(stationId);
                if (sysStationUser == null) {
                    SysStationUser stationUser = stationUserService.selectSysStationUserById(stationId);
                    stationMap.put(stationId,stationUser);
                    sysStationUser = stationUser;
                }
                if (sysStationUser != null) {
                    balanceVO.setStationName(sysStationUser.getStationName());
                    balanceVO.setEnterpriseId(sysStationUser.getEnterpriseId());
                }
            }
            if (StringUtils.isNotBlank(balanceVO.getMobilePhone()) && balanceVO.getEnterpriseId() != null) {
                String k = String.format("%d%s",balanceVO.getEnterpriseId(),balanceVO.getMobilePhone());
                SysAppUserInfoUser user = userMap.get(k);
                if (user == null) {
                    SysAppUserInfoUser query = new SysAppUserInfoUser();
                    query.setMobilePhone(balanceVO.getMobilePhone());
                    query.setStationId(balanceVO.getEnterpriseId());
                    SysAppUserInfoUser one = appUserInfoUserService.getOne(query);
                    userMap.put(k,one);
                    user = one;
                }
                if (user != null) {
                    balanceVO.setUserId(user.getUserId());
                    balanceVO.setRegisteDate(user.getRegisteDate());
                    balanceVO.setCustomerName(user.getBlogNickName());
                    balanceVO.setMemberCode(user.getMemberCode());
                }
            }
        }
        return userBalanceVOS;
    }

    @Override
    public UserBalanceSumVO sumUserBalanceVO(UserBalanceForm form) {
        UserBalanceSumVO sumVO = customerElectronicCardMapper.sumUserBalanceVO(form);
        sumVO.setReturnCashAmt(customerElectronicCardMapper.sumUserBalanceVOReturnCash(form).getReturnCashAmt());
        sumVO.setTotalAmt(MathUtil.add(sumVO.getAmt(),sumVO.getPresentAmt()));
        return sumVO;
    }

    @Override
    public Integral rechargeActivityGiveIntegral(String orderNo) {
        Integral integral=new Integral();
        integral.setTotalIntegral(0);
        integral.setPresentIntegral(0);

        CustomerCardUseRecord recordQuery = new CustomerCardUseRecord();
        recordQuery.setOrderNo(orderNo);
        CustomerCardUseRecord cardRecordByOrderNo = getCardRecordByOrderNo(recordQuery);
        integral=rechargeActivityGiveIntegral(cardRecordByOrderNo);
        return integral;
    }

    private CustomerCardUseRecord getCardRecordByOrderNo(CustomerCardUseRecord recordQuery) {
        List<CustomerCardUseRecord> customerCardUseRecords = customerCardUseRecordMapper.selectCustomerCardUseRecordList(recordQuery);
        if(customerCardUseRecords.size()>0){
            return customerCardUseRecords.get(0);
        }
        return null;
    }

    @Override
    public Integral rechargeActivityGiveIntegral(CustomerCardUseRecord cardRecordByOrderNo) {
        Integral integral=new Integral();
        integral.setTotalIntegral(0);
        integral.setPresentIntegral(0);
        CustomerCardSettingDetail form = new CustomerCardSettingDetail();

        form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_INTEGRAL);//积分
        form.setDelFlag("0");
        form.setCardType(cardRecordByOrderNo.getCardOilsType());
        form.setEnterpriseId(Long.valueOf(cardRecordByOrderNo.getEnterpriseId()));
        form.setStationId(Long.valueOf(cardRecordByOrderNo.getStationId()));
        form.setStatus("NORMAL");
        if(cardRecordByOrderNo.getPayType()==null){
            cardRecordByOrderNo.setPayType("xj");
        }
        form.setPayType(cardRecordByOrderNo.getPayType().equals("wx")?"wx":"xj");
        form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);
        form.setAmt(cardRecordByOrderNo.getAmt());

        SysAppUserInfoUser appUserInfo=new SysAppUserInfoUser();
        appUserInfo.setMobilePhone(cardRecordByOrderNo.getMobilePhone());
        appUserInfo.setStationId(cardRecordByOrderNo.getEnterpriseId());
        List<SysAppUserInfoUser> appUserInfos = appUserInfoMapper.selectAppUserInfoList(appUserInfo);
        if(appUserInfos.size()>0) {
            appUserInfo=appUserInfos.get(0);
        }else{
            return integral;
        }


        if(cardRecordByOrderNo.getAmt()!=null){
            CustomerCardSettingDetailContent content=customerCardSettingDetailContentMapper.selectMatchFirstDetailContent(form);
            if(content!=null){
                BigDecimal presentAmount = content.getPresentAmount();
                if(presentAmount==null){
                    return integral;
                }
                if(appUserInfo.getUserId()!=null) {
                    Long totalInteger = appUserInfo.getIntegral();
                    int presentIntegral= presentAmount.multiply(cardRecordByOrderNo.getAmt()).intValue();
                    if (presentIntegral>0) {
                        if(totalInteger==null){
                            totalInteger= (long) presentIntegral;
                        }else{
                            totalInteger=totalInteger+presentIntegral;
                        }
                        appUserInfo.setIntegral(totalInteger);
                        integral.setPresentIntegral(presentIntegral);
                        integral.setTotalIntegral(totalInteger.intValue());
                        appUserInfoMapper.updateAppUserInfo(appUserInfo);
                        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                        customerPointsRecord.setCreateTime(new Date());
                        customerPointsRecord.setIntegral((long) presentIntegral);
                        customerPointsRecord.setOrderNo(cardRecordByOrderNo.getOrderNo());
                        customerPointsRecord.setRecordType("+");
                        customerPointsRecord.setMobilePhone(appUserInfo.getMobilePhone());
                        customerPointsRecord.setUnionId(appUserInfo.getUnionId());
                        customerPointsRecord.setStationId(cardRecordByOrderNo.getStationId().longValue());
                        customerPointsRecord.setCustomerName(appUserInfo.getBlogNickName());
                        customerPointsRecord.setAction(integralTypeEnum.CONSUMEPRESENT);
                        customerPointsRecord.setCreateTime(DateUtils.getNowDate());
                        customerPointsRecord.setOrderNo(cardRecordByOrderNo.getOrderNo());

                        customerPointsRecordMapper.insertCustomerPointsRecord(customerPointsRecord);
                        customerPointsRecordService.wxgzhIntegralPush(customerPointsRecord);
                    }

                    return integral;
                }
            }


        }
        return integral;
    }

    @Override
    public CustomerCardUseRecord getReturnCashTotal(CustomerCardUseRecord customerCardUseRecord) {
        return customerCardUseRecordMapper.getReturnCashTotal(customerCardUseRecord);
    }

}
